package service

import (
	context "context"
	"go-locks/no-lock/db"
	"go-locks/no-lock/model"
	"go-locks/no-lock/proto"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
)

type Server struct{}

func (s Server) SellStock(ctx context.Context, request *proto.StockRequest) (*emptypb.Empty, error) {
	tx := db.DB.Begin()
	for _, info := range request.StockInfos {
		var stock model.Stock
		if result := tx.Where(&model.Stock{Goods: info.GoodsId}).First(&stock); result.RowsAffected == 0 {
			return nil, status.Error(codes.NotFound, "商品信息不存在")
		}
		if stock.Stocks < info.Num {
			// 库存不足 回滚事务
			tx.Rollback()
			return nil, status.Error(codes.ResourceExhausted, "库存不足")
		}
		stock.Stocks -= info.Num
		tx.Save(stock)
	}
	tx.Commit()
	return &emptypb.Empty{}, nil
}
